package com.atguigu.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author ：MJS
 * @date ：Created in 2021/4/26  19:30
 * @description：信号灯的意思
 * 案例：用争车位来表示
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //semaphore  服务限流---->争车位
        Semaphore semaphore = new Semaphore(3);//模拟3个停车位
        //6车抢3个车位

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                boolean flag=false;
                try{
                    //抢占资源
                    semaphore.acquire();
                    flag=true;
                    System.out.println(Thread.currentThread().getName()+"\t"+"占到车位");
                    try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                    System.out.println(Thread.currentThread().getName()+"\t"+"离开车位");
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    if(flag){
                        //释放资源
                        semaphore.release();
                    }

                }
            }, String.valueOf(i)).start();
        }

    }
}
